package com.oneday.nuo.base.security.jwt;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.oneday.nuo.base.security.user.NuoUser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;

/**
 *
 *
 *@author liushuai
 *@date 2020/7/28 19:58
 */
public class JwtUtil {



    /**
     * 生成签名
     * @param
     * @param
     * @return
     */
    public static String sign(NuoUser user, String tokenSecret){

        //私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(tokenSecret);
        //设置头信息
        HashMap<String, Object> header = new HashMap<>(2);
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        //附带username和userID生成签名
        JWTCreator.Builder builder = JWT.create().withHeader(header);
        builder.withClaim("userName",user.getUsername());
        builder.withClaim("userCode",user.getUserCode());

        return   builder.sign(algorithm);
    }




    public static boolean verity(String token,String tokenSecret){
        try {
            Algorithm algorithm = Algorithm.HMAC256(tokenSecret);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);
            return true;
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return false;
        } catch (JWTVerificationException e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 通过header头部的token得到userName
     * @return token中包含的用户名
     */
    public static String getUserName(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userName").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 通过header头部的token得到userCode
     * @return token中包含的用户名
     */
    public static String getUserCode(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userCode").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }
    public static JSONObject getAuths(String token){
        if(StrUtil.isEmpty(token)){
            return new JSONObject();
        }
        try {

            DecodedJWT jwt = JWT.decode(token);
            JSONObject json = new JSONObject(jwt.getClaim("auths").asString());
            return json;
        } catch (JWTDecodeException e) {
            return null;
        }
    }




}
